/**
 * Light-commons Project
 * http://light-commons.googlecode.com
 * Copyright (C) 2008 Jason Green
 * email: guileen@gmail.com
 *
 * License: Apache License 2.0 
 * (http://www.apache.org/licenses/LICENSE-2.0)
 *
 */
package org.lightmtv.response;

import javax.servlet.http.HttpServletResponse;

import org.lightcommons.util.StringUtils;
import org.lightcommons.web.MimeType;

/**
 * @author gl
 * @since Jun 27, 2008
 */
public abstract class AbstractContentResponse extends AbstractResponse {
	private String contentType;
	private String fileName;
	private String encoding;
	private int contentLength;
	private boolean download;
	private String fileNameEncoding="GBK";
	
	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setMimeType(MimeType mimeType) {
		this.contentType = mimeType.getContentType();
	}

	public void setContentTypeByExt(String ext) {
		this.contentType = MimeType.getContentType(ext);
	}

	public boolean isDownload() {
		return download;
	}

	public void setDownload(boolean download) {
		this.download = download;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public String getFileNameEncoding() {
		return fileNameEncoding;
	}

	public void setFileNameEncoding(String fileNameEncoding) {
		this.fileNameEncoding = fileNameEncoding;
	}

	public String getFileName() {
		return fileName;
	}
	
	public int getContentLength() {
		return contentLength;
	}
	
	/**
	 * @param fileName
	 *            the fileName to set
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
		if (!StringUtils.hasText(getContentType()) && StringUtils.hasLength(fileName)) {
			final String ext = StringUtils.getFilenameExtension(fileName);
			setContentType(MimeType.getContentType(ext));
		}

	}

	/**
	 * @param contentLength
	 *            the contentLength to set
	 */
	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	@Override
	public void send(HttpServletResponse response) {
		response.setContentType(contentType);
		if(StringUtils.hasText(encoding))
			response.setCharacterEncoding(encoding);
		else
			response.setCharacterEncoding("utf-8");
		if (StringUtils.hasLength(fileName)) {
			try {
				byte[] fileNameBytes;
				if(fileNameEncoding == null){
					fileNameBytes = fileName.getBytes("UTF-8");
				}else{
					fileNameBytes = fileName.getBytes(fileNameEncoding);
				}
				response.setHeader("Content-Disposition", "filename=\""
						+ new String(fileNameBytes, "ISO-8859-1") + "\"");
			} catch (final Exception e) {
			}
		}
		if (contentLength > 0) {
			response.setContentLength(contentLength);
		}
		super.send(response);
	}
}
